import React, {useState, useEffect, useRef} from 'react'
import { Loading, Dialog, Toast } from 'react-vant';
import BiwMeta from '@services/index'
import request from "@services/request";
import './index.less'

let timeSwitch = null
const NoLogin = (props) => {
  const [loadAccount, setLoadAccount] = useState(false)

  const biwSign = useRef({})

  useEffect(() => {
    init()
  }, [])

  const recommend_update = async () => {
    if (
      props.urlCode &&
      props.urlCode !== props.state.inviteUserAddress
    ) {
      const res = await request.post("app_server/recommend_update", {
        code: this.urlCode,
        sign
      });

      props.setState({
        ...props.state,
        inviteUserAddress: res.inviteUserAddress,
      })
    }
  }

  const getUser = async () => {
    const getData = async () => {
      const res = await request.get("app_server/user_info");
      props.setState(res);
    };

    await getData();
  }

  const loginSuccess = async (token) => {
    if (token) {
      localStorage.setItem("token", token);
      localStorage.setItem("account", biwSign.current.address || '');
    }
    await getUser();
    await recommend_update();
    props.dispatch.setUrlCode('')
    location.hash = "";
    // console.log('登录成功')
    props.dispatch.setIsLogin(true)
  }

  const login = async (params) => {
    const res = await request.post("app_server/eth_authorize", params);
    return res;
  };

  const openCodeInput = (sign) => {
    const confirm = async () => {
      const code = document.getElementById('codeInput').value

      if (!code) {
        Toast.info('请输入推荐码')
        setTimeout(() => {
          openCodeInput()
        }, 1000)
        return
      }

      const res = await login({ address: biwSign.current?.address, publicKey: biwSign.current?.publicKey, code, sign: biwSign.current?.signMessage, noMsg: true })
      // 判断是否直接进入系统
      if (res.token) {
        loginSuccess(res.token);
      } else {
        Toast.info(res.status)
        setTimeout(() => {
          openCodeInput()
        }, 1000)
      }
    }

    Dialog.alert({
      title: '请输入邀请码',
      closeable: false,
      theme: 'round-button',
      className: 'code-dialog',
      showConfirmButton: true,
      message: (
        <div className="code-input-dialog">
          <input type="text" id="codeInput" placeholder="请输入邀请码" />
          {/* <button onClick={() => confirm()}>确认</button> */}
        </div>
      )
    }).then(res => {
      console.log(res)
      confirm()
    })
  }

  const init = async () => {
    // openCodeInput()
    // props.dispatch.setIsLogin(true)
    // return


    const BM = new BiwMeta()
    const signList = await BM.sign()
    biwSign.current = signList.find((item) => item.name === 'BIW')

    if (!biwSign.current) {
      return Toast.fail('不存在BIWMeta链')
    }

    // const account = '1111'
    const accountLac = localStorage.getItem("account");
    // /* 判断是否本地token */
    console.log(accountLac, biwSign.current?.address)
    // return
    if (accountLac && accountLac === biwSign.current?.address) {
      localStorage.setItem("biwSign", JSON.stringify(biwSign.current));
      loginSuccess();
      return;
    }

    localStorage.removeItem("account")
    localStorage.removeItem("token")
    localStorage.removeItem("biwSign")

    localStorage.setItem("biwSign", JSON.stringify(biwSign.current));
    // this.loadAccount = true;
    setLoadAccount(true)

    const res = await login({ address: biwSign.current?.address, publicKey: biwSign.current?.publicKey, code: "", sign: biwSign.current?.signMessage, noMsg: true })
    // 判断是否直接进入系统
    if (res.token) {
      loginSuccess(res.token);
    } else {
      openCodeInput()
    }
  }

  return (
    <>
      <div className="no-login">
        <div className="no-login-content">
          <Loading type="spinner" />
          <span>{!loadAccount ? '钱包连接中' : '合约验证中'}</span>
        </div>
      </div>
    </>
  )
}

export default NoLogin;